// src/stores/product.js
import { defineStore } from 'pinia'
import {
  listAllProductsAPI,
  addProductAPI,
  updateProductAPI,
  deleteProductAPI,
  getProductAPI,
  toggleProductStatusAPI,
  searchProductByNameAPI
} from '@/api/productAPI'

export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    selectedProduct: null
  }),

  actions: {
    // 获取所有商品
    async fetchProducts() {
      this.loading = true
      try {
        const res = await listAllProductsAPI()
        
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 后端返回的是 List<ProductInfoDTO>
          if (Array.isArray(res.data)) {
            this.products = res.data
            this.total = res.data.length
          } else {
            this.products = []
            this.total = 0
          }
        } else {
          console.error('获取商品列表失败:', res?.message || '未知错误')
          this.products = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取商品失败:', error)
        this.products = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 根据商品名称搜索商品
    async searchProductsByName(name) {
      this.loading = true
      try {
        const res = await searchProductByNameAPI(name)

        if (res && (res.code === 0 || res.code === 200) && res.data) {
          if (Array.isArray(res.data)) {
            this.products = res.data
            this.total = res.data.length
          } else {
            this.products = []
            this.total = 0
          }
        } else {
          console.error('搜索商品失败:', res?.message || '未知错误')
          this.products = []
          this.total = 0
        }
      } catch (error) {
        console.error('搜索商品失败:', error)
        this.products = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 新增商品
    async addProduct(productData) {
      try {
        const res = await addProductAPI(productData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchProducts()
          return { success: true }
        } else {
          throw new Error(res?.message || '添加商品失败')
        }
      } catch (error) {
        console.error('新增商品失败:', error)
        throw error
      }
    },

    // 编辑商品
    async updateProduct(id, productData) {
      try {
        const res = await updateProductAPI(id, productData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchProducts()
          return { success: true }
        } else {
          throw new Error(res?.message || '更新商品失败')
        }
      } catch (error) {
        console.error('更新商品失败:', error)
        throw error
      }
    },

    // 删除商品
    async deleteProduct(id) {
      try {
        const res = await deleteProductAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchProducts()
          return { success: true }
        } else {
          throw new Error(res?.message || '删除商品失败')
        }
      } catch (error) {
        console.error('删除商品失败:', error)
        throw error
      }
    },

    // 获取单个商品详情
    async getProductById(id) {
      try {
        const res = await getProductAPI(id)
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          this.selectedProduct = res.data
          return res.data
        } else {
          throw new Error(res?.message || '获取商品详情失败')
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        throw error
      }
    },

    // 切换商品状态
    async toggleProductStatus(id) {
      try {
        const res = await toggleProductStatusAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchProducts()
          return { success: true }
        } else {
          throw new Error(res?.message || '切换商品状态失败')
        }
      } catch (error) {
        console.error('切换商品状态失败:', error)
        throw error
      }
    }
  }
})